package com.itheima.service.impl;

import com.itheima.mapper.CategoryMapper;
import com.itheima.pojo.Category;
import com.itheima.pojo.PageResult;
import com.itheima.pojo.R;
import com.itheima.service.CategoryService;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;


    @Override
    public R add(Category category) {

        int row = categoryMapper.insert(category);

        if(row<=0){
            return R.error("添加失败"); //code 0
        }
        return R.success("添加成功"); //code 1
    }

    @Override
    public R<PageResult> findPage(int page, int pageSize) {


        //4.1 把page 转换城 查询的起始索引
        int pageIndex = (page - 1)*pageSize;
        //4.查询数据
        List<Category> categoryList = categoryMapper.selectPage(pageIndex,pageSize);

        //5.封装PageResult 对象
        PageResult pageResult = new PageResult();
        pageResult.setRecords(categoryList);
        pageResult.setCurrent(page);
        pageResult.setSize(pageSize);
        int count = categoryMapper.selectCount();
        pageResult.setTotal(count);
        pageResult.setPages(count%pageSize == 0?count/pageSize:count/pageSize+1);

        return R.success(pageResult);
    }

    @Override
    public R removeById(long id) {

        int row =  categoryMapper.deleteById(id);

        if(row <= 0){
            return R.error("删除失败");
        }
        return R.success("删除成功");
    }
    @Override
    public R modify(Category category) {


        //4.调用方法修改数据库的数据
        int row = categoryMapper.updateById(category);


        if(row <=0){
            return R.error("修改失败");
        }

        return R.success("修改成功");
    }
}
